'use strict';
const crypto = require('crypto');

exports.main = async (event, context) => {
  const { username, password } = event;
  
  // 参数校验
  if (!username || !password) {
    return {
      code: 1,
      msg: '请输入用户名和密码'
    }
  }
  
  const db = uniCloud.database();
  const collection = db.collection('users');
  
  try {
    // 查找用户
    const userResult = await collection.where({
      username: username
    }).get();
    
    if (userResult.data.length === 0) {
      return {
        code: 2,
        msg: '用户名或密码错误'
      }
    }
    
    const user = userResult.data[0];
    
    // 验证密码
    const hash = crypto.pbkdf2Sync(password, user.salt, 1000, 64, 'sha512').toString('hex');
    if (hash !== user.password) {
      return {
        code: 2,
        msg: '用户名或密码错误'
      }
    }
    
    // 检查用户状态
    if (user.status !== 1) {
      return {
        code: 3,
        msg: '账号已被禁用'
      }
    }
    
    // 生成登录token
    const token = crypto.randomBytes(32).toString('hex');
    
    return {
      code: 0,
      msg: '登录成功',
      data: {
        userId: user._id,
        username: user.username,
        token: token
      }
    }
    
  } catch (e) {
    return {
      code: -1,
      msg: '登录失败，请稍后重试'
    }
  }
}; 